<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\api\BaseApiController;
use app\apps\model\Apps;
use app\apps\model\Group;
use app\version\model\Version;
use app\apps\model\Rule;
use think\helper\Str;

class App extends BaseApiController
{

    /**
     * 检查更新
     * url: http://域名/api/v1/app/version
     * doc: http://lutui.net/doc/app/check-update.html
     */
    public function version()
    {
        $curr = $this->data['version']; // 当前版本
        $last = Version::order('id', 'desc')->limit(1)->find();
        if ($last && $last->version != $curr) {
            return json(['url' => DOMAIN . $last->url]);
        }
        return json(['url' => '']);
    }

    /**
     * 应用列表
     * url: http://域名/api/v1/app/list
     * doc: http://lutui.net/doc/app/app-list.html
     */
    public function list()
    {
        $list = Group::with(['apps' => function ($query) {
            $query->order(['sort' => 'asc', 'id' => 'desc']);
            $query->with([
                'versions' => function ($query) {
                    $query->order('id', 'desc');
                    $query->limit(1);
                },
                'rules'
            ]);
        }])->order(['sort' => 'asc', 'id' => 'desc'])->select();
        $data = [];
        foreach ($list as $value) {
            $apps = [];
            if ($value->apps) {
                foreach ($value->apps as $app) {
                    if (Rule::get($app->id)) {
                        $apps[] = [
                            'name' => $app->name,
                            'icon' => $app->icon ? $app->icon : DOMAIN . $app->image,
                            'url' => 'app://' . $app->tag,
                        ];
                    }
                }
            }
            if ($apps) {
                $data[] = [
                    'name' => $value->name,
                    'apps' => $apps,
                ];
            }
        }
        return json($data);
    }

    /**
     * 应用短ID
     * url: http://域名/api/v1/app/id
     * doc: http://lutui.net/doc/app/app-id.html
     */
    public function id()
    {
        $id = $this->data['id'];
        $one = Apps::with([
            'versions' => function ($query) {
                $query->order('id', 'desc');
                $query->limit(1);
            },
            'rules'
        ])->where('tag', $id)->find();
        $url = $this->getAppUrl();
        if ($one && Rule::get($one->id)) {
            $url = $this->getAppUrl($one->versions);
        }
        return json(['url' => $url]);
    }

    // 读取应用的访问地址
    private function getAppUrl($arr = [])
    {
        if (!empty($arr)) {
            $url = $arr[0]['url'];
            if (Str::contains($url, 'http')) {
                return $url;
            }
            return DOMAIN . $url . '?cache=0';
        }
        return DOMAIN.'/static/system/__UNI__5FDB086.wgt';
    }
}
